package com.government.system.service.impl;

import cn.hutool.json.JSONUtil;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.government.common.exception.ServiceException;
import com.government.system.domain.Message;
import com.government.system.mapper.MessageMapper;
import com.government.system.service.IMessageService;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;


@Slf4j
@Transactional(rollbackFor = Exception.class)
@Service
public class MessageServiceImpl implements IMessageService {

    @Value(value = "${sms.accessKeyId}")
    private String accessKeyId;
    @Value(value = "${sms.accessKeySecret}")
    private String accessKeySecret;

    @Autowired
    private MessageMapper messageMapper;

    @Override
    public void sendSms(String phone, String content) throws ExecutionException, InterruptedException {

        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(accessKeyId)
                .accessKeySecret(accessKeySecret)
                .build());
        AsyncClient client = AsyncClient.builder()
                .region("cn-hangzhou") // Region ID
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                )
                .build();

        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .phoneNumbers(phone)
                .signName("透策")
                .templateCode("SMS_290110713")
                .templateParam("{\"code\":\"" + content + "\"}")
                .build();


        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);

        SendSmsResponse resp = response.get();
        client.close();
        log.info("对手机号为{}的设备发送短信结果如下{}", phone, JSONUtil.toJsonStr(resp));
        if ("OK".equals(resp.getBody().getCode())) {
            Message message = new Message();
            message.setContent(content);
            message.setCreateTime(new Date());
            message.setPhone(phone);
            messageMapper.insert(message);
        } else {
            throw new ServiceException("短信发送失败");
        }

    }
}
